import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {//index
    path: '/index',
    meta: { title: 'index' },
    component: () => import('../views/Index.vue'),
    children: [
      {//首页
        path: '/index/home',
        name: 'home',
        meta: { title: '首页' },
        component: () => import('../views/Index/Home'),
      },
      {//爆爆团
        path: '/index/tuan',
        name: 'tuan',
        meta: { title: '爆爆团' },
        component: () => import('../views/Index/Tuan'),
      },
      {//订单
        path: '/index/order',
        name: 'order',
        meta: { title: '订单' },
        component: () => import('../views/Index/Order'),
      },
      {//我的
        path: '/index/mine',
        name: 'mine',
        meta: { title: '我的' },
        component: () => import('../views/Index/Mine'),
      },
      {
        path: '/',
        redirect: '/index/Home'
      },
    ]
  },
  {//详情
    path: '/detail/:id',
    name: 'detail',
    meta: { title: '详情' },
    component: () => import('../views/Detail.vue')
  },
  {//登录
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: () => import('../views/Login.vue')
  },
  {//注册
    path: '/register',
    name: 'register',
    meta: { title: '注册' },
    component: () => import('../views/Register.vue')
  },
  {//搜素
    path: '/search',
    name: 'search',
    meta: { title: '注册' },
    component: () => import('../views/Search.vue')
  },
  {//店铺关注
    path: '/collect',
    name: 'collect',
    meta: { title: '店铺关注' },
    component: () => import('../views/Collected')
  },
  {//地址
    path: '/address',
    name: '/address',
    meta: { title: '我的收货地址' },
    component: () => import('../views/Address'),
  },
  {
    path: '/newaddress',
    name: 'newaddress',
    meta: { title: '新增地址' },
    component: () => import('../views/Newaddress')
  },
  {
    path: '/modifyaddress/:addinfo',
    name: 'modifyaddress',
    meta: { title: '修改地址' },
    component: () => import('../views/Modifyaddress')
  },
  {
    path: '/',
    redirect: '/index/Home'
  },
  {//404
    path: '*',
    name: 'notfinde',
    meta: { title: '错误' },
    component: () => import('../views/NotFined.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  var token = localStorage.getItem('token');
  // 只有在登录后才可以跳转到订单页和我的页面
  if (to.path == '/index/order' || to.path == '/index/mine') {
    if (token) {//已经登录
      next();
    } else {//未登录
      next('/login');
    }
  } else {//其他页面( 非订单页 )
    next();//必须手动调用该函数, 否则无法完成路由跳转
  }
})

export default router
